<?php
// +----------------------------------------------------------------------
// | snake
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2022 http://baiyf.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: NickBai <1902822973@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\model;

use think\Model;
use think\Db;

class BalanceModel extends Model
{
    // 确定链接表名
    protected $table = 'xl_balance';

    /**
     * 根据搜索条件获取用户列表信息
     * @param $where
     * @param $offset
     * @param $limit
     */
    public function getUsersByWhere($where, $offset, $limit)
    {

        return $this->alias('a')->field( 'a.*,xl_user.user_name as admin_name, xl_front_user.username')
            ->join('xl_user',  'a.admin_id = xl_user.id')
            ->join('xl_front_user',  'a.user_id = xl_front_user.id')
            ->where($where)->limit($offset, $limit)->order('id desc')->select();
//            ->where('xl_front_user.username','like' ,'%张三%')->limit($offset, $limit)->order('id desc')->select();

//        return $this->field($this->table . '.*')
//            ->where($where)->limit($offset, $limit)->order('id desc')->select();
    }


    /**
     * 根据搜索条件获取所有的用户数量
     * @param $where
     */
    public function getAllUsers($where)
    {
        if ($where) {
            return count($this->alias('a')->field( 'a.*,xl_user.user_name as admin_name, xl_front_user.username')
                ->join('xl_user',  'a.admin_id = xl_user.id')
                ->join('xl_front_user',  'a.user_id = xl_front_user.id')
                ->where($where)->order('id desc')->select());
        }
        return $this->where($where)->count();
    }

    /**
     * 插入管理员信息
     * @param $param
     */
    public function insertUser($param)
    {
        try{
            $param['ctime'] = time();
            $result =  $this->validate('UserValidate')->save($param);
            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{

                return msg(1, url('frontUser/index'), '添加用户成功');
            }
        }catch(PDOException $e){

            return msg(-2, '', $e->getMessage());
        }
    }

    /**
     * 编辑管理员信息
     * @param $param
     */
    public function editUser($param)
    {
        try{

            $result =  $this->validate('UserValidate')->save($param, ['id' => $param['id']]);

            if(false === $result){
                // 验证失败 输出错误信息
                return msg(-1, '', $this->getError());
            }else{
                return msg(1, url('frontUser/index'), '编辑用户成功');
            }
        }catch(PDOException $e){
            return msg(-2, '', $e->getMessage());
        }
    }

    /**
     * 根据管理员id获取角色信息
     * @param $id
     */
    public function getOneUser($id)
    {
        return $this->where('id', $id)->find();
    }

    /**
     * 删除管理员
     * @param $id
     */
    public function delUser($id)
    {
        try{

            $this->where('id', $id)->delete();
            return msg(1, '', '删除管理员成功');

        }catch( PDOException $e){
            return msg(-1, '', $e->getMessage());
        }
    }

    /**
     * 根据用户名获取管理员信息
     * @param $name
     */
    public function findUserByName($name)
    {
        return $this->where('user_name', $name)->find();
    }

    /**
     * 更新管理员状态
     * @param array $param
     */
    public function updateStatus($param = [], $uid)
    {
        try{
            $this->where('id', $uid)->update($param);
            return msg(1, '', 'ok');
        }catch (\Exception $e){

            return msg(-1, '', $e->getMessage());
        }
    }

    //修改用户余额
    public function upBalance($params)
    {
        try{
            $adminArr = session('userInfo');
            $userInfo = $this->where('id', $params['id'])->find();
            if (!$userInfo) {
                return msg(-1, '', '暂无数据');
            }
            //开启事务
            Db::startTrans();
            $data = [
                'money'=> $userInfo['money'],
                'user_id' =>  $params['id'],
                'admin_id' =>  $adminArr['id'],
                'new_money'=> $params['new_money'],
                'types' => $params['types'],
                'ctime' => time(),
            ];
            $rsl = Db::name('Balance')->insertGetId($data);

            if (!$rsl) {
                throw new \Exception('日志保存失败！');
            }
            $useRsl = $this->where('id', $params['id'])->update(['money' => $params['new_money'], 'utime' => time()]);
            if (!$useRsl) {
                throw new \Exception('修改用户余额失败！');
            }
            Db::commit();
            return msg(1, url('frontUser/index'), '操作成功');
        }catch (\Exception $e){
            //回滚
            Db::rollback();
            return msg(-1, '', $e->getMessage());
        }
    }
}